import { ref } from 'vue';
import { convertCurrency } from '@/services/apiCurrency';

export function useCurrencyConvert(showPicker, isFirst) {
  const firstAmount = ref(0);
  const firstLabel = ref('CNY');

  const secondAmount = ref(0);
  const secondLabel = ref('USD');

  async function convert(flag) {
    if (flag === 'first') {
      const amount = await convertCurrency(
        firstLabel.value.toLowerCase(),
        secondLabel.value.toLowerCase(),
        firstAmount.value
      );

      secondAmount.value = Number(amount.toFixed(2));
      return;
    }

    const amount = await convertCurrency(
      secondLabel.value.toLowerCase(),
      firstLabel.value.toLowerCase(),
      secondAmount.value
    );
    firstAmount.value = Number(amount.toFixed(2));
  }

  const onConfirm = ({ selectedOptions }) => {
    showPicker.value = false;

    if (isFirst.value) {
      firstLabel.value = selectedOptions[0].text;
    } else {
      secondLabel.value = selectedOptions[0].text;
    }

    if (firstLabel.value === secondLabel.value) {
      if (isFirst.value) {
        secondAmount.value = firstAmount.value;
      } else {
        firstAmount.value = secondAmount.value;
      }

      return;
    }

    convert(isFirst ? 'first' : 'second');
  };

  return {
    firstAmount,
    firstLabel,
    secondAmount,
    secondLabel,

    onConfirm,
    convert,
  };
}
